<?php


namespace app\api\controller\v1;

use app\api\exception\BaseException;
use app\api\validate\GoodsScene;
use app\api\validate\OrdersScene;
use app\api\validate\RefundScene;
use DateTime;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Request;

/**
 * Class Orders
 * @package app\api\controller\v1
 * 下单（订单）
 */
class Orders extends BaseException
{
    /**
     * 不需要登录方法
     */
    protected $noAuth = ['login'];

    /**
     *
     * 获取下单列表
     */
    public function getOrderList()
    {
        $data = Request::param();
        $search = [

        ];
        if (isset($data["sort"]) && $data["sort"] == "+id") {
            $order = ["id" => "asc"];
        } else {
            $order = ["id" => "desc"];
        }

        /**
         * 单一模糊查询开始
         */

        //产品品牌模糊查询
        if (isset($data["name"]) && !empty($data["name"])) {
            $search[] = ["name", "like", "%" . $data["name"] . "%"];
        }

        if (isset($data["telephone"]) && !empty($data["telephone"])) {
            $search[] = ["telephone", "like", "%" . $data["telephone"] . "%"];
        }

        if (isset($data["starttime"]) && !empty($data["starttime"])) {
           
            array_push($search, ["create_time", "between time", $data["starttime"]]);
        }
        /**
         * 单一模糊查询结束
         */
        /**
         *多条件查询开始
         */
        //数据状态筛选查询
        //  if (isset($data["data_state"]) && $data["data_state"] != '') {
        array_push($search, ["data_state", "=", 1]);
        //}
        //上架状态筛选查询
        if (isset($data["status"]) && $data["status"] != '') {
            array_push($search, ["status", "=", $data["status"]]);
        }
        if (isset($data["order_class"]) && $data["order_class"] != '') {
            array_push($search, ["order_class", "=", $data["order_class"]]);
        }
        if (isset($data["user_type"]) && $data["user_type"] != '') {
            array_push($search, ["user_type", "=", $data["user_type"]]);
        }
        if ($this->user_type == 4) {
            array_push($search, ["status", "=", 1]);
        }

        $orderlist = Db::name("orders")->where($search)->order($order)->page($data["page"], $data["limit"])->select()->toArray();
        $count = Db::name("orders")->where($search)->count();
        foreach ($orderlist as $key => $value) {
            $countNum = 0;
            $countRetailPrice = 0;
            $countAgencyPrice = 0;
            $countCostPrice = 0;
            $orderGoodsList = Db::name("order_goods")->where(["data_state" => 1, "order_id" => $value["id"]])->select()->toArray();
            foreach ($orderGoodsList as $key1 => $value1) {
                $goodsImgsArray = explode(",", $orderGoodsList[$key1]["imgs"]);
                $countNum = $orderGoodsList[$key1]["num"] + $countNum;
                $countRetailPrice = $orderGoodsList[$key1]["retail_price"] + $countRetailPrice;
                $countAgencyPrice = $orderGoodsList[$key1]["agency_price"] + $countAgencyPrice;
                $countCostPrice = $orderGoodsList[$key1]["cost_price"] + $countCostPrice;
                if (count($goodsImgsArray) != 0) {
                    for ($i = 0; $i < count($goodsImgsArray); $i++) {
                        $goodsImgsArray[$i] = "http://" . $_SERVER['HTTP_HOST'] . $goodsImgsArray[$i];
                    }
                    $orderGoodsList[$key1]["imgs"] = $goodsImgsArray;
                }

            }
            $orderlist[$key]["order_goods"] = $orderGoodsList;
            $orderlist[$key]["countNum"] = $countNum;
            $orderlist[$key]["retail_price"] = $countRetailPrice;
            $orderlist[$key]["agency_price"] = $countAgencyPrice;
            $orderlist[$key]["cost_price"] = $countCostPrice;
        }
        $list = [
            "total" => $count,
            "page" => $data["page"],
            "limit" => $data["limit"],
            "list" => $orderlist,
        ];
        return self::Success($list, '获取成功', 200);
    }

    /**
     *
     * 库内创建订单
     * 库内Inside 1 库外Out 2
     */
    public function createOrder()
    {
        $request = Request::param();
        try {
            validate(OrdersScene::class)
                ->scene('add')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $userinfo = Db::name("account")->where(["id" => $this->user_id])->find();
        if ($request["province"] != "") {
            $addressInfo = explode(" ", $request["province"]);
            $province = $addressInfo[0];
            $city = $addressInfo[1];
            $county = $addressInfo[2];
        }
        $insertData = [
            "user_id" => $this->user_id,
            "user_type" => $this->user_type,
            "express_name" => isset($request["express_name"]) ? $request["express_name"] : "",
            "name" => isset($request["name"]) ? $request["name"] : "",
            "telephone" => isset($request["telephone"]) ? $request["telephone"] : "",
            "province" => empty($province) ? "" : $province,
            "city" => empty($city) ? "" : $city,
            "county" => empty($county) ? "" : $county,
            "address" => isset($request["address"]) ? $request["address"] : "",
            "remark" => $userinfo["real_name"],
            "status" => 0,
            "real_postage" => isset($request["real_postage"]) ? number_format($request["real_postage"], 2) : 0,
            "actual_postage" => isset($request["actual_postage"]) ? number_format($request["actual_postage"], 2) : 0,
            "explain_msg" => empty($request["explain_msg"]) ? "" : $request["explain_msg"],
            "order_class" => isset($request["order_class"]) ? $request["order_class"] : 1,
            'create_time' => date("Y-m-d H:i:s", time()),
            'update_time' => date("Y-m-d H:i:s", time()),
            'create_time_d' => time(),
            'data_state' => 1,
            'order_state' => 1,
        ];
        $order_id = Db::name("orders")->insertGetId($insertData);
        $orderGoodsList = $request["goods"];
        $count_price = 0;
        foreach ($orderGoodsList as $key => $value) {
            $insertData = [
                "order_id" => $order_id,
                "goods_id" => isset($value["id"]) ? $value["id"] : 0,
                "goods_color" => $value["color"],
                "goods_size" => $value["size"],
                "imgs" => empty($value["imgs"]) ? "" : implode(",", $value["imgs"]),
                "num" => $value["num"],
                "goods_name" => $value["goods_name"],
                "agency_price" => empty($value["agency_price"]) ? "" : $value["agency_price"],
                "cost_price" => empty($value["cost_price"]) ? "" : $value["cost_price"],
                "retail_price" => empty($value["retail_price"]) ? "" : $value["retail_price"],
                "depot_id" => empty($value["depot_id"]) ? 0 : $value["depot_id"]["id"],
                "depot_name" => empty($value["depot_id"]) ? "" : $value["depot_id"]["name"],
                'create_time' => date("Y-m-d H:i:s", time()),
                'update_time' => date("Y-m-d H:i:s", time()),
                'data_state' => 1,
            ];
            Db::name("order_goods")->insert($insertData);
            $count_price = number_format($value["num"] * $value["retail_price"], 2) + $count_price;
        }
        Db::name("orders")->where(["id" => $order_id])->update(["price" => $count_price]);
        $returnGoodsInfo = Db::name("orders")->where(["id" => $order_id])->find();

        $countNum = 0;
        $countRetailPrice = 0;
        $countAgencyPrice = 0;
        $countCostPrice = 0;
        $orderGoodsList = Db::name("order_goods")->where(["data_state" => 1, "order_id" => $value["id"]])->select()->toArray();
        foreach ($orderGoodsList as $key1 => $value1) {
            $goodsImgsArray = explode(",", $orderGoodsList[$key1]["imgs"]);
            $countNum = $orderGoodsList[$key1]["num"] + $countNum;
            $countRetailPrice = $orderGoodsList[$key1]["retail_price"] + $countRetailPrice;
            $countAgencyPrice = $orderGoodsList[$key1]["agency_price"] + $countAgencyPrice;
            $countCostPrice = $orderGoodsList[$key1]["cost_price"] + $countCostPrice;
            if (count($goodsImgsArray) != 0) {
                for ($i = 0; $i < count($goodsImgsArray); $i++) {
                    $goodsImgsArray[$i] = "http://" . $_SERVER['HTTP_HOST'] . $goodsImgsArray[$i];
                }
                $orderGoodsList[$key1]["imgs"] = $goodsImgsArray;
            }

        }
        $returnGoodsInfo["order_goods"] = $orderGoodsList;
        $returnGoodsInfo["countNum"] = $countNum;
        $returnGoodsInfo["retail_price"] = $countRetailPrice;
        $returnGoodsInfo["agency_price"] = $countAgencyPrice;
        $returnGoodsInfo["cost_price"] = $countCostPrice;

        if ($order_id) {
            return self::Success($returnGoodsInfo, "添加成功", 200);
        } else {
            return self::Error($request, '添加失败', 10002);
        }
    }

    /**
     * 批量删除
     */
    public function batchUpdateState()
    {
        $request = Request::param();
        try {
            validate(OrdersScene::class)
                ->scene('update_state')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "data_state" => $request["data_state"],
            "update_time" => date("Y-m-d H:i:s", time()),
        ];
        $check = Db::name("orders")->where(["id" => $request["id"]])->find();
        if ($check) {
            $result = Db::name("orders")->where(["id" => $request["id"]])->update($updateData);
            if ($result) {
                return self::Success(null, "操作成功", 200);
            } else {
                return self::Error(null, '操作失败', 10002);
            }
        } else {
            return self::Error(null, '数据不存在', 10002);
        }
    }

    public function batchDelete()
    {
        $request = Request::param();
        $ids = explode(",", $request["ids"]);
        if (count($ids) != 0) {
            for ($i = 0; $i < count($ids); $i++) {
                $updateData = [
                    "data_state" => 0,
                    "update_time" => date("Y-m-d H:i:s", time()),
                ];
                Db::name("orders")->where(["id" => $ids[$i]])->update($updateData);
            }
        }
        return self::Success(null, "删除成功", 200);
    }

    /**
     *
     * 更新订单信息
     */
    public function updateOrderInfo()
    {
        $request = Request::param();
        $insertData = [
            "express_name" => isset($request["express_name"]) ? $request["express_name"] : "",
            "name" => isset($request["name"]) ? $request["name"] : "",
            "telephone" => isset($request["telephone"]) ? $request["telephone"] : "",
            "province" => empty($request["province"]) ? "" : $request["province"],
            "city" => empty($request["city"]) ? "" : $request["city"],
            "county" => empty($request["county"]) ? "" : $request["county"],
            "address" => isset($request["address"]) ? $request["address"] : "",
            "real_postage" => isset($request["real_postage"]) ? number_format($request["real_postage"], 2) : 0,
            "explain_msg" => empty($request["explain_msg"]) ? "" : $request["explain_msg"],
            'update_time' => date("Y-m-d H:i:s", time()),

        ];
        $check = Db::name("orders")->where(["id" => $request["id"]])->update($insertData);
        if ($check) {
            $orderGoodsList = $request["order_goods"];
            $count_price = 0;
            foreach ($orderGoodsList as $key => $value) {
                $insertData = [
                    "goods_color" => $value["goods_color"],
                    "goods_size" => $value["goods_size"],
                    "num" => $value["num"],
                    "goods_name" => $value["goods_name"],
                    "retail_price" => empty($value["retail_price"]) ? "" : $value["retail_price"],
                    'update_time' => date("Y-m-d H:i:s", time()),
                ];
                if (!isset($value["id"]) && empty($value["id"])) {
                    $Data = [
                        "order_id" => $request["id"],
                        "agency_price" => 0.00,
                        "cost_price" => 0.00,
                        "depot_id" => 0,
                        "depot_name" => "",
                        "data_state" => 1,
                        "goods_color" => $value["goods_color"],
                        "goods_size" => $value["goods_size"],
                        "num" => $value["num"],
                        "goods_name" => $value["goods_name"],
                        "retail_price" => empty($value["retail_price"]) ? "" : $value["retail_price"],
                        'update_time' => date("Y-m-d H:i:s", time()),
                        'create_time' => date("Y-m-d H:i:s", time()),
                    ];
                    Db::name("order_goods")->insert($Data);
                } else {
                    Db::name("order_goods")->where(["id" => $value["id"]])->update($insertData);
                }


                $count_price = number_format($value["num"] * $value["retail_price"], 2) + $count_price;
            }
            Db::name("orders")->where(["id" => $request["id"]])->update(["price" => $count_price]);
            return self::Success(null, "更新成功", 200);
        } else {
            return self::Error(null, "更新失败", 200);
        }


    }

    /**
     * @return void
     * 批量修改邮费
     */
    public function batchUpdatePostage()
    {

    }

    /**
     *
     * 批量修改审核状态
     */
    public function batchUpdateStatus()
    {
        $request = Request::param();
        try {
            validate(OrdersScene::class)
                ->scene('update_status')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $updateData = [
            "status" => $request["status"],
            "update_time" => date("Y-m-d H:i:s", time()),
        ];
        $check = Db::name("orders")->where(["id" => $request["id"]])->find();
        if ($check) {
            $result = Db::name("orders")->where(["id" => $request["id"]])->update($updateData);
            if ($result) {
                return self::Success(null, "操作成功", 200);
            } else {
                return self::Error(null, '操作失败', 10002);
            }
        } else {
            return self::Error(null, '操作失败', 10002);
        }
    }
}